package com.rc.saas.tenant.service.member;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.mapper.member.RcMemberLevelSettingMapper;
import com.rc.saas.tenant.model.member.RcMemberLevelSetting;
import com.rc.saas.tenant.model.member.RcMemberLevelSettingExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class MemeberLevelServiceImpl implements MemeberLevelService {

    @Autowired
    private RcMemberLevelSettingMapper memberLevelSettingMapper;

    @Override
    public RcMemberLevelSettingMapper getMapper() {
        return memberLevelSettingMapper;
    }

    @Override
    public PageInfo<RcMemberLevelSetting> listPageMemberLevel(Integer pageNo, Integer pageSize, String levelName) {
        PageHelper.startPage(pageNo, pageSize);
        List<RcMemberLevelSetting> list = memberLevelSettingMapper.listMemberLevel(levelName);
        return new PageInfo<>(list);
    }

    public void addMemberLevel(RcMemberLevelSetting memberLevelSetting) {
        if (memberLevelSetting != null && StringUtils.isEmpty(memberLevelSetting.getMemberLevel())) {
            memberLevelSetting.setMemberLevel(memberLevelSetting.getLevelName());
        }
        memberLevelSettingMapper.updateMemberLevelForFreeze(memberLevelSetting.getLevelName());

        if ("0".equals(memberLevelSetting.getCycleType())) {
            memberLevelSetting.setBeginTime(new Date());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.YEAR, 1);
            memberLevelSetting.setEndTime(calendar.getTime());
        }
        memberLevelSettingMapper.insertSelective(memberLevelSetting);
    }

    @Override
    public List<RcMemberLevelSetting> loadLevels() {
        RcMemberLevelSettingExample example = new RcMemberLevelSettingExample();
        example.createCriteria().andMemberLevelNotEqualTo("V0");
        return memberLevelSettingMapper.selectByExample(example);
    }

    @Override
    public List<RcMemberLevelSetting> getParLevels() {
        return memberLevelSettingMapper.getParLevels();
    }
}
